/**
 * @description 登录校验
 */

const { jwtVerify } = require('../utils/jwt')
const { ErrorRes } = require('../res-model/index')
const { loginCheckFailInfo } = require('../res-model/failInfo/index')

function getTokenValue(ctx) {
  // Authorization: Bearer xxx
  const { authorization } = ctx.header
  if (!ctx.header || !authorization) {
    return false
  }
  if (typeof authorization === 'string') {
    const params = authorization.trim().split(' ')
    if (params.length === 2) {
      const scheme = params[0]
      const credentials = params[1]
      if (/^Bearer$/i.test(scheme)) {
        return credentials
      }
    }
  }
  return false
}

/**
 * 登录校验
 * @param {Object} ctx ctx
 * @param {function} next next
 */
module.exports = async function loginCheck(ctx, next) {
  // 失败信息
  const errRes = new ErrorRes(loginCheckFailInfo)

  const token = getTokenValue(ctx)
  if (!token) {
    ctx.body = errRes
    return
  }

  try {
    const userInfo = await jwtVerify(token)
    ctx.userInfo = userInfo
    await next()
  } catch (ex) {
    ctx.body = errRes
    return
  }
}
